;$(function () {
    var id = $("#id").val();
    var flagId =$("#flagId").val();
    contribute_validator();

    showExamInfo();

});

var current={
    examTopic:{
        id:"",
        examId:"",//考试id
        title:"",//题目
        type:"",//题目类型
        grade:"",//题目分数

        buildingExamAnswerEOList:[],//题目选项
    },
    examAnswer:{//头目选项
        title:"",//答案内容
        isAnswer:"",//是否是答案
        sort:"",//答案排序
    },
    sorted:['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'],
    count:0,
}

var tale = new $.tale();//弹框

function contribute_validator() {
    $("#global-form").validator({
        fields: {
            name: {
                rule: "required;",
                msg: {
                    required: "必填!"
                }
            },
            totalNumber: {
                rule: "required;",
                msg: {
                    required: "必填!"
                }
            },
            totalPoints: {
                rule: "required;",
                    msg: {
                    required: "必填!"
                }
            },
            passingGrade: {
                rule: "required;",
                    msg: {
                    required: "必填!"
                }
            },
            startTime: {
                rule: "required;",
                msg: {
                    required: "必填!"
                }
            },
            endTime: {
                rule: "required;",
                msg: {
                    required: "必填!"
                }
            },
            remark: {
                rule: "required;",
                msg: {
                    required: "必填!"
                }
            },
        },
        invalid: function (form, errors) {
            return;
        },
        //验证成功
        valid: function (form) {
            saveInfo();
        },
    });
}

function saveInfo() {
    var json =$("#global-form").serializeFormJSON();
    $.ajax({
        url: ctxPath+"/party/exam/saveExamInfo",
        type: 'POST',
        data: json,
        success: function (d) {
            var success = d.success;
            if (success) {
                $("#id").val(d.data);
                tale.alertOk({
                    text: '考试信息保存成功'
                });
                showExamContent();
                getList();
            } else {
                tale.alertError(result.message || '保存失败');
            }
        }
    });
}

function getList(pageNo, pageSize) {
    var id = $("#id").val();
    if (typeof(pageNo) == 'undefined') {
        pageNo = 1;
    }

    if (typeof(pageSize) == 'undefined') {
        pageSize = 15;
    }

    $.ajax({
        url: ctxPath+"/party/exam/getTopicPage",
        type: 'POST',
        data: {pageNo: pageNo, pageSize: pageSize,examId:id},
        success: function (d) {
            if (d.data != null) {
                var html = "";
                $.each(d.data.dataList, function (i, item) {
                    html += toHtml(item,i);
                })
                $("#list_result").html(html);
                getPage(d.data.pages, d.data.total,id);
            }

        }
    });
}

//分页
function getPage(pageCount, totalCount,id) {
    kkpager.total = pageCount;//总页码
    kkpager.totalRecords = totalCount;//总条数
    kkpager.generPageHtml({
        pno: 0,
        mode: 'click',//默认值是link，可选link或者click
        click: function (n) {
            getList(n, 15,id);
            this.selectPage(n);
            return false;
        }
    });
}

function toHtml(data,i) {

    var edit = "<button type='button' class='btn btn-primary btn-sm' onclick='edit(" + data.id + ")'><i class=\"fa fa-edit\"></i>编辑</button>";
    var del = "<button type='button' class='btn btn-danger btn-sm' onclick='del(" + data.id + ")'><i class=\"fa fa-trash-o\"></i>删除</button>";

    var typeName="";
    if(data.type == '1'){
        typeName = '单选';
    }else if(data.type == '2'){
        typeName = '多选';
    }else if(data.type == '3'){
        typeName = '判断';
    }else {
        //do nothing
    }

    var index = parseInt(i) + 1;
    return '<tr>'
        + '<td class="text-center">'
        + index
        + '</td>'
        + '<td class="text-center">'
        + data.title
        + '</td>'
        + '<td class="text-center">'
        + typeName
        + '</td>'
        + '<td class="text-center">'
        + data.grade
        + '</td>'
        + '<td class="text-center">'
        + edit
        + del
        + '</td>'
        + '</tr>';
}

function showExamInfo(){
    $("#examInfo").css('display','block');//显示
    $("#examContent").css('display','none');//隐藏
    $("#t1").addClass("tablab");
    $("#t2").removeClass("tablab");
}

function showExamContent(){
    $("#examInfo").css('display','none');//隐藏
    $("#examContent").css('display','block');//显示
    $("#t2").addClass("tablab");
    $("#t1").removeClass("tablab");
}

function showModal(){
    $("#myModal").modal({
        backdrop:'static'
    });
}

function clearDiv(){
    $("#answer").empty();
    var subjectType = $("#radioChoosen").find("input[type='radio']:checked").val();
    if(subjectType == '3'){
        $("#addAnswers").css('display','none');
        var htmlLine = ' <div class="form-group" id="index'+current.count+'"><div class="col-md-2"><input type="text" name="sortIndex" value="A" readonly="readonly" class="form-control"/></div><div class="col-md-6"><input type="text" class="form-control" name="examAnswer"/></div>'
            + '<div class="col-md-1"><input type="radio" class="form-control" name="answerCompment"/></div></div>'
            + '<div class="form-group" id="index'+current.count+'"><div class="col-md-2"><input type="text" name="sortIndex" value="B" readonly="readonly" class="form-control"/></div><div class="col-md-6"><input type="text" class="form-control" name="examAnswer"/></div>'
            + '<div class="col-md-1"><input type="radio" class="form-control" name="answerCompment"/></div></div>';

        $("#answer").append(htmlLine);
    }else{
        $("#addAnswers").css('display','block');
    }
}

function addAnswer(){

    // var checkboxer = '<input type="checkbox" id="userId'+data.id +'" value="'+data.id+'" onclick="checkUser(this)"/>';
    // if(ids.indexOf(data.id.toString()) > -1){
    //     checkboxer = '<input type="checkbox" id="userId'+data.id +'" value="'+data.id+'" onclick="checkUser(this)" checked="checked"/>';
    // }
    var subjectType = $("#radioChoosen").find("input[type='radio']:checked").val();
    if(subjectType == '1'){
        var htmlLine = ' <div class="form-group" id="index'+current.count+'"><div class="col-md-2"><input type="text" name="sortIndex" class="form-control"/></div><div class="col-md-6"><input type="text" class="form-control" name="examAnswer"/></div>'
            + '<div class="col-md-1"><input type="radio" class="form-control" name="answerCompment"/></div>'
            + '<div class="col-md-2"><input type="button" class="btn-danger" value="删除" onclick="delLine('+current.count+')"/></div></div>';

        $("#answer").append(htmlLine);
    }else if(subjectType == '2'){
        var htmlLine = ' <div class="form-group" id="index'+current.count+'"><div class="col-md-2"><input type="text" name="sortIndex" class="form-control"/></div><div class="col-md-6"><input type="text" class="form-control" name="examAnswer"/></div>'
            + '<div class="col-md-1"><input type="checkbox" class="form-control" name="answerCompment"/></div>'
            + '<div class="col-md-2"><input type="button" class="btn-danger" value="删除" onclick="delLine('+current.count+')"/></div></div>';

        $("#answer").append(htmlLine);
    }else {
        //do nothing
    }
    current.count++;
}

function delLine(id){
    $("#index"+id).remove();
}




function saveExamSubjects(){
    current.examTopic.id = $("#topicId").val();
    current.examTopic.examId = $("#id").val();
    current.examTopic.title =$("#title").val();
    current.examTopic.grade =$("#grade").val();
    current.examTopic.type = $("#radioChoosen").find("input[type='radio']:checked").val();
    // if(current.examTopic.type == '2'){
    //     $("#answer").find("input[name='answerCompment']").each(function(i,element){
    //         current.examAnswer.sort = current.sorted[i];
    //         if($(this).prop("checked")){
    //             current.examAnswer.isAnswer = "0";
    //         }else {
    //             current.examAnswer.isAnswer = "1";
    //         }
    //
    //         current.examAnswer.title = $(this).parent().siblings().find("input[name='examAnswer']").val();
    //    });
    // }else {
    //     $("#answer").find("input[type='radio']").each(function(i,element){
    //         current.examAnswer.sort = current.sorted[i];
    //         if($(this).prop("checked")){
    //             current.examAnswer.isAnswer = "0";
    //         }else {
    //             current.examAnswer.isAnswer = "1";
    //         }
    //
    //         current.examAnswer.title = $(this).parent().siblings().find("input[name='examAnswer']").val();
    //     });
    // }
    var flag = 0;
    $("#answer").find("input[name='answerCompment']").each(function(i,element){
        current.examAnswer = new Object();
        current.examAnswer.sort = $(this).parent().siblings().find("input[name='sortIndex']").val();
        if(current.sorted.indexOf(current.examAnswer.sort) == -1){
            tale.alertError('答案前标不合法，请重新输入');
            flag = 1 ;
            clearAttr();
        }else{
            if($(this).prop("checked")){
                current.examAnswer.isAnswer = "0";
            }else {
                current.examAnswer.isAnswer = "1";
            }

            current.examAnswer.title = $(this).parent().siblings().find("input[name='examAnswer']").val();
            current.examTopic.buildingExamAnswerEOList.push(current.examAnswer);
        }

    });

    if(flag == 0){
        $.ajax({
            url: ctxPath+"/party/exam/saveExamSubjects",
            type: 'POST',
            dataType:'json',
            contentType:'application/json',
            data: JSON.stringify(current.examTopic),
            success: function (d) {
                var success = d.success;
                if (success) {
                    tale.alertOk({
                        text: '考试信息保存成功'
                    });
                    clearAttr();
                    showExamContent();

                } else {
                    clearAttr();
                    tale.alertError(result.message || '保存失败');

                }
            }
        });
    }

}

function clearAttr(){
    current.examTopic = new Object();
    current.count = 0;
    current.examTopic.buildingExamAnswerEOList = new Array();
    current.examAnswer = new Object();

    $("#title").val("");
    $("#grade").val("");
    $("#answer").empty();
    $("#myModal").modal('hide');
    $("#type1").prop("checked","checked");
    $("#addAnswers").css('display','block');
    getList();
}

function clearDynmicAttr(){
    current.examTopic = new Object();
    current.count = 0;
    current.examTopic.buildingExamAnswerEOList = new Array();
    current.examAnswer = new Object();

    $("#answer").empty();
}


function del(id) {
    $.ajax({
        url: ctxPath+"/party/exam/delTopic",
        type: 'POST',
        data: {id:id},
        success: function (d) {
            if(d.success){
                alert(d.message);
            }

            getList();
        },
        error: function () {
            alert("异常！");
        }
    });
}

function edit(id){
    $.ajax({
        url: ctxPath+"/party/exam/editExamTopic",
        type: 'GET',
        data: {id:id},
        success: function (d) {
            if(d.success){
                $("#topicId").val(d.data.id);
                clearDynmicAttr();
                createModal(d.data);
            }
        },
        error: function () {
            alert("异常！");
        }
    });
}

function createModal(data){
    $("#title").val(data.title);
    $("#grade").val(data.grade);
    $("#radioChoosen").find("input[type='radio']").each(function(i,element){
        if(data.type == $(this).val()){
            $(this).prop("checked","checked");
        }
    });

    var buildingExamAnswerEOList = data.buildingExamAnswerEOList;
    if(buildingExamAnswerEOList != null){
        if(data.type == '2'){//checkbox
            for(var i=0;i<buildingExamAnswerEOList.length;i++){
                var checked = '';
                if(buildingExamAnswerEOList[i].isAnswer == '0'){
                    checked = 'checked';
                }

                var htmlLine = ' <div class="form-group" id="index'+current.count+'"><div class="col-md-2"><input type="text" name="sortIndex" class="form-control" value="'+buildingExamAnswerEOList[i].sort+'"/></div><div class="col-md-6"><input type="text" class="form-control" name="examAnswer" value="'+buildingExamAnswerEOList[i].title+'"/></div>'
                    + '<div class="col-md-1"><input type="checkbox" class="form-control" name="answerCompment" '+ checked+'/></div>'
                    + '<div class="col-md-2"><input type="button" class="btn-danger" value="删除" onclick="delLine('+current.count+')"/></div></div>';

                $("#addAnswers").css('display','block');
                $("#answer").append(htmlLine);
                current.count++;
            }
        }else {//radio
            for(var i=0;i<buildingExamAnswerEOList.length;i++){

                var checked = '';
                if(buildingExamAnswerEOList[i].isAnswer == '0'){
                    checked = 'checked="checked"';
                }
                var disabled = '';
                if(data.type == '3'){
                    disabled = 'disabled="disabled"';
                }

                var htmlLine = ' <div class="form-group" id="index'+current.count+'"><div class="col-md-2"><input type="text" name="sortIndex" class="form-control" value="'+buildingExamAnswerEOList[i].sort+'" '+disabled+'/></div><div class="col-md-6"><input type="text" class="form-control" name="examAnswer" value="'+buildingExamAnswerEOList[i].title+'"/></div>'
                    + '<div class="col-md-1"><input type="radio" class="form-control" name="answerCompment" '+checked+'/></div>'
                    + '<div class="col-md-2"><input type="button" class="btn-danger" value="删除" onclick="delLine('+current.count+')"/></div></div>';

                if(data.type == '3'){
                    $("#addAnswers").css('display','none');
                }else{
                    $("#addAnswers").css('display','block');
                }
                $("#answer").append(htmlLine);
                current.count++;


            }
        }
    }else {
        $("#type1").prop("checked","checked");
        $("#addAnswers").css('display','block');
    }


    showModal();
}
